import mongoose from 'mongoose'
import { DB_URL } from '../config/index'
mongoose.set('useFindAndModify', false)
// mongoose.set('useCreateIndex', true) // 解决警告
mongoose.Promise = require('bluebird')

// 连接
mongoose.connect(DB_URL, {
	useNewUrlParser: true,
	useUnifiedTopology: true,
    useCreateIndex: true
})

// 连接成功
mongoose.connection.on('connected', async function () {
	console.log('Mongoose connection open to ', DB_URL)
    const DlyAdminShopWhite = require('../model/dlyadminshopwhite')
	const shopWhiteList = await DlyAdminShopWhite.find({}).limit(1000).skip(0)
    if(shopWhiteList.length > 0) {
       const shopWList = shopWhiteList.map(res => {
            return res.shopId
        })
        const mergedArray = Array.from(new Set([...global.WhiteList, ...shopWList]))
        global.WhiteList = mergedArray
    }
})

// 连接异常
mongoose.connection.on('error', function (err) {
	console.log('Mongoose connection error: ' + err)
})

// 断开连接
mongoose.connection.on('disconnected', function () {
	console.log('Mongoose connection disconnected')
})

export default mongoose
